/**
 * 客户资源录入脚本支持
 */
var key = $("#keyname").val();
var modifydata = null;

//页面载入初始化
$( "body" ).ready( function( e )
{
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}

	// 键盘事件
	$( "body" ).bind( "keyup", bodyKeyupHandler );

	// 初始化
	button_bind();
	init_editors();

	// 初始化选择
	if( !empty( modifydata ) )
	{
		setInitData( modifydata );
	}
} );

//--------------------------------------------------------------------------
//
//	consultant_client.php
//
//--------------------------------------------------------------------------

var _editor = [];

function button_bind()
{
	$( "#btnSubmit" ).bind( "click", function()
	{
		submit_form();
	} );

	$( "a[rel='btnItemShow']" ).click( show_hide_list );
	$( "a[rel='btnScoreShow']" ).click( show_hide_list );
	$( "a[rel='btnDelItemGroup']" ).click( del_item_group );

	$( "a#btnAddItemGroup" ).click( add_item_group );
	$( "a#btnAddScoreGroup" ).click( add_score_group );
}

function del_item_group( e )
{
	if( confirm( "确定移除该选项组吗？" ) )
	{
		$( this ).parent().parent().remove();
		if( $( "#items div" ).length == 0 )
			$( "#items" ).prepend( "<span class='caption'>请点击左侧“+”添加选项组。</span>" );
	}
}

function del_score_group( e )
{
	if( confirm( "确定移除该评分规则吗？" ) )
	{
		$( this ).parent().parent().remove();
		if( $( "#items div" ).length == 0 )
			$( "#items" ).prepend( "<span class='caption'>请点击左侧“+”添加评分规则。</span>" );
	}
}

function show_hide_list( e )
{
	var ul = $( this ).parent().parent().find( "ul" );
	if( ul.visible() )
	{
		ul.hide();
	}
	else
	{
		ul.show();
	}
}

function set_item_group( g, d )
{
	if( empty( d ) )
		return;

	g.find( "input[name='topic']" ).val( d.topic );
	g.find( "ul" ).empty();

	var size = d.items.length;

	for( var i = 0; i < size; i++ )
	{
		add_item( g, d.items[ i ].q, d.items[ i ].i );
	}
}

function add_item_group( e, id )
{
	$( "#items > span" ).remove();

	var size = $( "#items .item_group" ).length;

	if(size==0){
		id = "ask0";
	}else if(size==1){
		id = "ask1";
	}else if(size==2){
		id = "ask2";
	}else if(size==2){
		id = "ask2";
	}else if(size==3){
		id = "ask3";
	}else if(size==4){
		id = "ask4";
	}else if(size==5){
		id = "ask5";
	}else if(size==6){
		id = "ask6";
	}else if(size==7){
		id = "ask7";
	}else if(size==8){
		id = "ask8";
	}else if(size==9){
		id = "ask9";
	}else if(size==10){
		id = "ask10";
	}else if(size==11){
		id = "ask11";
	}else if(size==12){
		id = "ask12";
	}else if(size==13){
		id = "ask13";
	}else if(size==14){
		id = "ask14";
	}else{
		alert( "选项组最多添加 15个。" );
		return;
	}
	
	var h = "<div id=\"" + id + "\" class=\"item_group\" style=\"background-image: url(../resource/img/t/num-"
			+ ( size + 1 ) + ".png);\">";

	h += "<p>";
	h += "<label>分组名称：</label>";
	h += "<input type=\"text\" name=\"topic\" size=\"50\" />";
	h += "<a rel=\"btnDelItemGroup\" class=\"del\" title=\"点击删除该选项组\"></a>";
	h += "<a rel=\"btnAddItem\" class=\"add\" title=\"点击添加新的选项\"></a>";
	h += "<a rel=\"btnItemShow\" class=\"search\" title=\"显示/隐藏选项列表\"></a>";
	h += "<a rel=\"btnItemExpand\" class=\"arrow\" title=\"展开此选项组并收起其它组\"></a>";
	h += "<a rel=\"btnItemUp\" class=\"arrow-up\" title=\"向上\"></a>";
	h += "<a rel=\"btnItemDown\" class=\"arrow-down\" title=\"向下\"></a>";
	h += "</p>";
	h += "<ul></ul>";
	h += "</div>";

	if( size > 0 )
	{
		$( "#items .item_group:last" ).after( h );
	}
	else
	{
		$( "#items" ).prepend( h );
	}

	var group = $( "#items .item_group:last" );
	bind_item_group_event( group );
	add_item( group );

	return group;
}

function bind_item_group_event( g )
{
	g.find( "a[rel='btnDelItemGroup']" ).click( del_item_group );
	g.find( "a[rel='btnAddItem']" ).click( function()
	{
		add_item( g );
	} );
	g.find( "a[rel='btnItemShow']" ).click( show_hide_list );

	g.find( "a[rel='btnItemExpand']" ).click( { self: g }, function( e )
	{
		$( "#items div.item_group" ).each( function( id )
		{
			var div = $( this );
			var ul = div.find( "ul" );

			if( div.attr( "id" ) == e.data.self.attr( "id" ) )
			{
				ul.show();
			}
			else
			{
				ul.hide();
			}
		} );
	} );

	g.find( "a[rel='btnItemUp']" ).click( item_group_up );
	g.find( "a[rel='btnItemDown']" ).click( item_group_down );

}

function item_group_up()
{
	var g = $( this ).parent().parent();
	var g2 = null;
	var index = g.index();

	if( index > 0 )
	{
		g2 = $( "td#items div.item_group" ).eq( index - 1 );
		g2.before( g );
	}
}

function item_group_down()
{
	var g = $( this ).parent().parent();
	var g2 = null;
	var index = g.index();
	var size = $( "td#items div.item_group" ).length;

	if( index < size - 1 )
	{
		g2 = $( "td#items div.item_group" ).eq( index + 1 );
		g2.after( g );
	}
}

function add_item( g, q, i )
{
	var h = "<li style='list-style:decimal inside;'>";

	//h += "<label>题目：</label>";
	h += "<input type=\"text\" name=\"question\" size=\"50\" />";
	h += "<span></span>";
	h += "<label>选项：</label>";
	h += "<input type=\"text\" name=\"items\" size=\"30\" />";
	h += "<a rel=\"btnDelItem\" class=\"del\" title=\"点击删除该选项\"></a>";
	h += "</li>";

	g.find( "ul" ).append( h );

	// 尝试设置初始数据
	q = empty( q ) ? "" : q;
	i = empty( i ) ? "" : i;

	var li = g.find( "ul li:last" );
	li.find( "input[name='question']" ).val( q );
	li.find( "input[name='items']" ).val( i );
	li.find( "a[rel='btnDelItem']" ).click( function()
	{
		$( this ).parent().remove();
	} );

	li.find( "input[name='items']" ).bind( { focusin: format_items_symbol, focusout: format_items_symbol } );
}

function set_score_group( g, d )
{
	if( empty( d ) )
		return;

	var topic = empty( d.topic ) ? "" : d.topic;

	g.find( "input[name='group_name']" ).val( topic );
	g.find( "ul" ).empty();

	// 来源列表
	var size = d.source.length;
	for( var i = 0; i < size; i++ )
	{
		add_score_source_single( g.find( "span[rel='score_source']" ), d.source[ i ] );
	}

	// 结果列表
	size = d.scores.length;

	for( var i = 0; i < size; i++ )
	{
		add_score( g, d.scores[ i ].s1, d.scores[ i ].s2, d.scores[ i ].r );
	}
}

/**
 * 根据指定的选项组，添加相应的规则组
 * 
 * @param e 点击事件对象
 * @param id 选项组ID，用于绑定评分规则组，进行联动
 */
function add_score_group( e, id )
{
	$( "#scores > span" ).remove();

	var size = $( "#scores .score_group" ).length;

	if(size==0){
		id = "ask0";
	}else if(size==1){
		id = "ask1";
	}else if(size==2){
		id = "ask2";
	}else if(size==2){
		id = "ask2";
	}else if(size==3){
		id = "ask3";
	}else if(size==4){
		id = "ask4";
	}else if(size==5){
		id = "ask5";
	}else if(size==6){
		id = "ask6";
	}else if(size==7){
		id = "ask7";
	}else if(size==8){
		id = "ask8";
	}else if(size==9){
		id = "ask9";
	}else if(size==10){
		id = "ask10";
	}else if(size==11){
		id = "ask11";
	}else if(size==12){
		id = "ask12";
	}else if(size==13){
		id = "ask13";
	}else if(size==14){
		id = "ask14";
	}else{
		alert( "选项组最多添加 15个。" );
		return;
	}

	id = empty( id ) ? hash( 12 ) : id;
	var h = "<div id=\"" + hash( 12 ) + "\" rel=\"" + id
			+ "\" class=\"score_group\" style=\"background-image:url(../img/num-" + ( size + 1 )
			+ ".png);\">";

	h += "<p>";
	h += "<label>分组名称：</label>";
	h += "<input type=\"text\" name=\"group_name\" size=\"50\" />";
	h += "<a rel=\"btnDelScoreGroup\" class=\"del\" title=\"点击删除该评分规则\"></a>";
	h += "<a rel=\"btnAddScore\" class=\"add\" title=\"点击添加新的评分规则\"></a>";
	h += "<a rel=\"btnScoreShow\" class=\"search\" title=\"显示/隐藏评分规则列表\"></a>";
	h += "<a rel=\"btnScoreExpand\" class=\"arrow\" title=\"展开此规则组并收起其它组\"></a>";
	h += "<a rel=\"btnScoreUp\" class=\"arrow-up\" title=\"向上\"></a>";
	h += "<a rel=\"btnScoreDown\" class=\"arrow-down\" title=\"向下\"></a>";
	h += "</p>";
	h += "<p>";
	h += "<label>分数来源：</label>";
	h += "<span rel=\"score_source\">";
	h += "</span>";
	h += "<a rel=\"btnAddSource\" class=\"add\" title=\"点击添加新来源\"></a>";
	h += "</p>";
	h += "<ul></ul>";
	h += "</div>";

	if( size > 0 )
	{
		$( "#scores .score_group:last" ).after( h );
	}
	else
	{
		$( "#scores" ).prepend( h );
	}

	var group = $( "#scores .score_group:last" );
	bind_score_group_event( group );
	add_score( group );

	return group;
}

function bind_score_group_event( g )
{
	g.find( "a[rel='btnDelScoreGroup']" ).click( del_score_group );
	g.find( "a[rel='btnAddScore']" ).click( function()
	{
		add_score( g );
	} );
	g.find( "a[rel='btnScoreShow']" ).click( show_hide_list );
	g.find( "a[rel='btnAddSource']" ).click( add_score_source );

	g.find( "a[rel='btnScoreExpand']" ).click( { self: g }, function( e )
	{
		$( "#scores div.score_group" ).each( function( id )
		{
			var div = $( this );
			var ul = div.find( "ul" );

			if( div.attr( "id" ) == e.data.self.attr( "id" ) )
			{
				ul.show();
			}
			else
			{
				ul.hide();
			}
		} );
	} );

	g.find( "a[rel='btnScoreUp']" ).click( score_group_up );
	g.find( "a[rel='btnScoreDown']" ).click( score_group_down );

}

function score_group_up()
{
	var g = $( this ).parent().parent();
	var g2 = null;
	var index = g.index();

	if( index > 0 )
	{
		g2 = $( "td#scores div.score_group" ).eq( index - 1 );
		g2.before( g );
	}
}

function score_group_down()
{
	var g = $( this ).parent().parent();
	var g2 = null;
	var index = g.index();
	var size = $( "td#scores div.score_group" ).length;

	if( index < size - 1 )
	{
		g2 = $( "td#scores div.score_group" ).eq( index + 1 );
		g2.after( g );
	}
}

var _cur_score_source_obj;

function add_score_source( e )
{
	var selected = [];

	_cur_score_source_obj = $( this ).parent().find( "span[rel='score_source']" );
	_cur_score_source_obj.find( ">span" ).each( function( idx )
	{
		selected.push( $( this ).attr( "rel" ) );
	} );

	parent.selector.setCallback( add_socre_callback );
	parent.selector.open( selected, $( "td#items" ) );
}

function add_socre_callback( arr )
{
	for( var i = 0; i < arr.length; i++ )
	{
		add_score_source_single( _cur_score_source_obj, arr[ i ] );
	}
}

function add_score_source_single( tar, id )
{
	var item = $( "#" + id );
	var topic = item.find( "input[name='topic']" ).val();
	topic = empty( topic ) ? "选项组(" + ( item.index() + 1 ) + ")" : topic;

	var h = "<span class=\"rect quote\" style=\"margin-right:2px;\" rel=\"" + id + "\"><span>" + topic
			+ "</span><a rel=\"btnDel\" class=\"del\" title=\"点击删除该来源\"></a></span>";

	var span = tar.find( "span[rel='" + id + "']" );
	if( span.length > 0 )
	{
		span.find( "span" ).text( topic );
	}
	else
	{
		tar.append( h );
	}

	var btn = tar.find( "span[rel='" + id + "'] a[rel='btnDel']" );
	btn.unbind( "click" );
	btn.click( function( e )
	{
		$( this ).parent().remove();
	} );
}

function add_score( g, s1, s2, r )
{
	var h = "<li style='list-style:decimal inside;'>";

	h += "<label>分数为";
	h += "<input type=\"text\" name=\"score_1\" size=\"3\" />";
	h += "至";
	h += "<input type=\"text\" name=\"score_2\" size=\"3\" />";
	h += "分时，结果为：";
	h += "</label>";
	h += "<a rel=\"btnStress\" class=\"red\" title=\"用红色文本强调突出内容\">[ 强调 ]</a>";
	h += "<a rel=\"btnDelItem\" class=\"del\" title=\"点击删除该评分规则\"></a>";
	h += "<br>";
	h += "<div rel=\"result\" class=\"rect\" contenteditable=\"true\">评分结果</div>";
	h += "</li>";

	g.find( "ul" ).append( h );

	// 尝试设置初始数据
	s1 = empty( s1 ) && s1 != 0 ? "" : s1;
	s2 = empty( s2 ) && s1 != 0 ? "" : s2;
	r = empty( r ) ? "" : r;

	var li = g.find( "ul li:last" );
	li.find( "input[name='score_1']" ).val( s1 );
	li.find( "input[name='score_2']" ).val( s2 );
	li.find( "div[rel='result']" ).html( r );
	li.find( "a[rel='btnDelItem']" ).click( function()
	{
		$( this ).parent().remove();
	} );

	li.find( "a[rel='btnStress']" ).click( stress_text );

	// 重新缓存可编辑区域
	init_editors();
}

function stress_text( e )
{
	var hbox = $( this ).parent().find( "div[rel='result']" );
	var wrap = hbox.find( ">span[rel='STRESS']" );
	var html = hbox.html();

	if( wrap.length > 0 )
	{
		hbox.html( wrap.html() );
	}
	else
	{
		hbox.html( "<span rel=\"STRESS\" style=\"color:#ff0000;\">" + html + "</span>" );
	}
}

function format_items_symbol( e )
{
	var val = $( this ).val();

	val = $.trim( val );
	val = val.replace( /，/ig, "," );
	val = val.replace( /：/ig, ":" );
	val = val.replace( /\s*,\s*/ig, "," );
	val = val.replace( /\s*:\s*/ig, ":" );

	$( this ).val( val );
}

function init_editors()
{
	_editor = [];

	$( "div[contenteditable='true']" ).each( function()
	{
		_editor.push( $( this ).attr( "id" ) );
	} );
}

//--------------------------------------------------------------------------
//
//	数据提交
//
//--------------------------------------------------------------------------

function setInitData( d )
{
	if( !empty( d ) )
	{
		key = d.key;

		$( "#topic" ).val( d.topic );
		$( "#desc" ).html( d.desc );

		// 通用定义
		var id = null;
		var group = null;
		var val = null;
		var ns = null;

		// 设置选项组
		//		var size = d.item.length;
		//
		//		for( var i = 0; i < size; i++ )
		//		{
		//			// 添加选项分组
		//			var id = d.item[ i ].id;
		//			var g = add_item_group( null, id );
		//
		//			// 设置分组数据
		//			set_item_group( g, d.item[ i ] );
		//		}
		for( ns in d.item )
		{
			// 设置分组数据
			val = d.item[ ns ];
			id = val.id;
			group = add_item_group( null, id );
			set_item_group( group, val );
		}

		// 设置评分结果组
		//		size = d.score.length;
		//
		//		for( var i = 0; i < size; i++ )
		//		{
		//			// 设置评分规则
		//			var id = d.score[ i ].id;
		//			var group = add_score_group( null, id );
		//			set_score_group( group, search_score_data( d.score, id ) );
		//		}

		for( ns in d.score )
		{
			// 设置评分规则
			val = d.score[ ns ];
			id = val.id;
			group = add_score_group( null, id );
			set_score_group( group, search_score_data( d.score, id ) );
		}

		// 收起所有选项组和评分组
		$( "td#items div.item_group ul" ).hide();
		$( "td#scores div.score_group ul" ).hide();
	}
	else
	{
		key = null;

		$( "#topic" ).val( "" );
		$( "#desc" ).html( "" );

		$( "td#items" ).find( ">span" ).remove();
		$( "td#scores" ).find( ">span" ).remove();
	}
}

function search_score_data( data, id )
{
	for( var ns in data )
	{
		if( data[ ns ] && data[ ns ].id == id )
			return data[ ns ];
	}

	return null;
}

function submit_form()
{
	var data = {};

	// 待更新的数据
	data.id = $("#askId").val();

	// 分析问卷选项数据
	var item_groups = {};

	$( "#items div.item_group" ).each( function( id )
	{
		var it = parse_item_group( $( this ) );
		item_groups[ it.id ] = it;
	} );

	// 分析问卷评分规则数据
	var score_groups = {};
	var ps = true;

	score_group_tar = $( "#scores div.score_group" );

	score_group_tar.each( function( id )
	{
		var p = parse_score_group( $( this ) );

		// 未选择来源
		if( p == false )
		{
			ps = false;
			return false;
		}

		score_groups[ p.id ] = p;
	} );

	// 若数据分析失败，则终止提交
	if( !ps )
		return;

	// 组织提交数据
	data.topic = $( "#topic" ).val();
	data.desc = htmlfilter( $( "#desc" ).html() );
	data.item = JSON.stringify( item_groups );
	data.score = JSON.stringify( score_groups );

	$.post( "ask_add_go.json", data, function( value )
	{
		//var d = $.parseJSON( value );
		alert("操作成功");
	} );
}

function parse_item_group( g )
{
	var items = [];
	var id = g.attr( "id" );
	var topic = g.find( "input[name='topic']" ).val();

	g.find( "ul li" ).each( function( id )
	{
		var q = $( this ).find( "input[name='question']" ).val();
		var i = $( this ).find( "input[name='items']" ).val();
		items.push( { q: q, i: i } );
	} );
	return { id: id, topic: topic, items: items };
}

function parse_score_group( g )
{
	var scores = [];
	var id = g.attr( "rel" );// 与 item_group 存储相同的 id，便于以后比对
	var topic = g.find( "input[name='group_name']" ).val();

	g.find( "ul li" ).each( function( id )
	{
		var score_1 = $( this ).find( "input[name='score_1']" ).val();
		var score_2 = $( this ).find( "input[name='score_2']" ).val();
		var result = $( this ).find( "div[rel='result']" ).html();

		result = htmlfilter( result );
		scores.push( { s1: score_1, s2: score_2, r: result } );
	} );

	var sources = [];
	g.find( "span[rel='score_source']>span" ).each( function( idx )
	{
		sources.push( $( this ).attr( "rel" ) );
	} );

	/*if( sources.length == 0 )
	{
		infopad.err( "分数数据来源未选择。" );
		return false;
	}*/

	return { id: id, topic: topic, source: sources, scores: scores };
}

//--------------------------------------------------------------------------
//
//	methods
//
//--------------------------------------------------------------------------

function bodyKeyupHandler( e )
{
	if( e.ctrlKey && e.which == 13 )
	{
		submit_form();
	}
	else if( e.ctrlKey && e.shiftKey && e.which == 70 )// ctrl+shift+f
	{
		var edt = $( document.activeElement );
		var id = edt.attr( "id" );

		if( _editor.indexOf( id ) > -1 )
		{
			edt.html( htmlfilter( edt.html() ) );
		}
	}
}
